package com.zhaolulu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaolulu.common.constant.OrderStatus;
import com.zhaolulu.common.constant.PayStatus;
import com.zhaolulu.common.exception.LogicException;
import com.zhaolulu.domain.*;
import com.zhaolulu.domain.dto.PayDto;
import com.zhaolulu.mapper.OrderMapper;
import com.zhaolulu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ChannelService channelService;

    @Autowired
    private VendingMachineService vendingMachineService;


    @Autowired
    private PolicyService policyService;

    @Autowired
    private PartnerService partnerService;

    @Override
    public Order createOrder(PayDto payDto, String platform) {
        //1. 查询货道
        Channel channel = channelService.getChanneleByInnerCodeAndSku(payDto.getInnerCode(), payDto.getSkuId());
        if (channel == null) {
            throw new LogicException("该商品已售空");
        }
        //2. 查询设备
        VendingMachine vm = vendingMachineService.getVendingMachineByInnerCode(payDto.getInnerCode());
        if (vm == null) {
            throw new LogicException("设备不存在");
        }
        //3. 封装订单对象
        Order order = new Order();
        order.setSkuId(channel.getSkuId());// 商品ID
        order.setSkuName(channel.getSku().getSkuName());// 商品名称
        order.setChannelCode(channel.getChannelCode());// 货道编号
        order.setOpenId(payDto.getOpenId());// 小程序端的openId
        order.setPayType(platform);// 封装平台名称
        order.setPayStatus(PayStatus.PAY_STATUS_NOPAY);// 支付状态：未支付
        order.setStatus(OrderStatus.ORDER_STATUS_CREATE);// 订单状态：创建
        order.setOrderNo(payDto.getInnerCode() + System.nanoTime());// 订单编号
        order.setInnerCode(vm.getInnerCode());// 设备编号
        order.setNodeId(vm.getNodeId());// 点位ID
        order.setRegionId(vm.getRegionId());// 区域ID
        order.setPartnerId(vm.getPartnerId());// 合作商id
        order.setBusinessType(vm.getBusinessType());// 商圈类型
        order.setAddr(vm.getAddr());// 设备地址
        order.setCreateTime(LocalDateTime.now());
        order.setPrice(channel.getSku().getPrice());// 商品价格
        // 计算售价金额
        // 获取自动售货机对应的策略
        Policy policy = policyService.getById(vm.getPolicyId());
        // 如果策略存在，则使用策略中的折扣率
        if (policy != null) {
            BigDecimal discount = new BigDecimal(policy.getDiscount());//折扣比例
            BigDecimal price = new BigDecimal(channel.getSku().getPrice());//原价
            int realPrice = price.multiply(discount).divide(new BigDecimal(100), 0, RoundingMode.HALF_UP).intValue(); //计算真实价格
            order.setAmount(realPrice);
        }
        // 3-3计算合作商账单分账金额
        Partner partner = partnerService.getById(vm.getPartnerId());
        // 如果订单金额低于10分钱，不进行分账
        if (channel.getSku().getPrice() < 10) {
            order.setBill(0);
        } else {
            BigDecimal amount = new BigDecimal(order.getAmount()); //价格
            BigDecimal ratio = new BigDecimal(partner.getProfitRatio());//比例
            // 分成金额公式：(价格 * 比例) / 100
            int bill = amount.multiply(ratio).divide(new BigDecimal(100), 0, RoundingMode.HALF_UP).intValue();
            order.setBill(bill);
        }
        order.setAmount(1);// todo 开发期间，暂时写死为1分钱
        //4. 保存订单
        this.save(order);
        return order;
    }
    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @Override
    public Order getByOrderNo(String orderNo) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(Order::getOrderNo, orderNo);
        return this.getOne(qw);
    }
}

